"""
Case Type   : 资源池化集群系统内部使用工具
Case Name   : 备份过程中进行主备切换
Create At   : 2024/04/19
Owner       : @kyleze
Description :
    1.主机上初始化目录
    2.主机上添加备份实例
    3.主机上执行全量备份，同时执行主备切换
Expect      :
    1.成功
    2.成功
    3.备份失败
History     :
"""

import os
import unittest

from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.ComThread import ComThread

from yat.test import Node
from yat.test import macro


@unittest.skipIf(
    "dms" not in Common().get_sh_result(
    Node("PrimaryDbUser"), f"source {macro.DB_ENV_PATH}; "
    f"cm_ctl query -Cvidp"), "非资源池化环境不执行")
class SharedStorageGsProbackup(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.constant = Constant()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.st1_sh = CommonSH('Standby1DbUser')
        self.com = Common('PrimaryDbUser')
        self.pri_node = Node(node='PrimaryDbUser')
        self.st1_node = Node(node='Standby1DbUser')
        self.database = self.pri_node.db_name
        self.port = self.pri_node.db_port
        self.parent_path = os.path.dirname(macro.DB_INSTANCE_PATH)
        self.backup_path = os.path.join(self.parent_path,
                                        "backupset/backup_dir_009")
        self.instance_name = 'probackup_009'
        self.log.info("-----检查数据库状态是否正常-----")
        status = self.primary_sh.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status)
        cmd = f'source {macro.DB_ENV_PATH};' \
              f'cat $DSS_HOME/cfg/dss_vg_conf.ini |cut -d ":" -f 1'
        vgname_infor = self.pri_node.sh(cmd).result().strip()
        self.vgname = "+" + vgname_infor.split('\n')[0].strip() + \
                      ",+" + vgname_infor.split('\n')[1].strip()

    def test_gs_pro_backup(self):
        step = '--step1:主机上初始化目录 expect:成功--'
        self.log.info(step)
        result = self.primary_sh.exec_pro_backup_init(self.backup_path)
        self.log.info(result)
        self.assertTrue(result, "执行失败:" + step)

        step = '--step2:主机上添加备份实例，instance-id设为0 expect:成功--'
        self.log.info(step)
        result = self.primary_sh.exec_pro_back_add(
            self.backup_path, self.instance_name,
            f"--enable-dss --instance-id 0 --vgname='{self.vgname}'")
        self.log.info(result)
        self.assertTrue(result, "执行失败:" + step)

        step = '--step3:主机上执行全量备份，同时执行主备切换 expect:主备切换失败--'
        self.log.info(step)
        backup_thread = ComThread(
            self.primary_sh.exec_pro_backup_backup,
            args=(self.backup_path, self.instance_name, 'full',
                  f"{self.pri_node.db_name}",
                  f"--vgname='{self.vgname}' -j 128", True))
        switchover_cmd = f'sleep 2; source {macro.DB_ENV_PATH};' \
                         f'cm_ctl switchover -n 2 -D {macro.DB_INSTANCE_PATH} '
        switchover_thread = ComThread(self.com.get_sh_result,
                                      args=(self.st1_node,switchover_cmd,))
        backup_thread.setDaemon(True)
        switchover_thread.setDaemon(True)
        backup_thread.start()
        switchover_thread.start()
        backup_thread.join()
        switchover_thread.join()
        backup_msg = backup_thread.get_result()
        switchover_msg = switchover_thread.get_result()
        self.log.info(backup_msg)
        self.log.info(switchover_msg)
        self.assertIn('ERROR', backup_msg, '执行失败:' + step)
        self.assertIn(self.constant.cm_switchover_success_msg,
                      switchover_msg, '执行失败:' + step)

    def tearDown(self):
        self.log.info('----清理环境----')
        result = self.primary_sh.exec_cm_ctl('switchover', '-a')
        clear_cmd = f"rm -rf {self.backup_path}"
        self.log.info(clear_cmd)
        clear_msg = self.pri_node.sh(clear_cmd).result()
        self.log.info(result)
        self.log.info(clear_msg)
        self.assertIn(self.constant.cm_switchover_success_msg,
                      result, '恢复集群主备失败')
        self.assertIn('', clear_msg, '删除目录失败')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")

